package com.meida.module.bus.provider.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.ExportInterceptor;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.module.bus.client.entity.BusScholartyrant;
import com.meida.module.bus.client.enums.UserTypeEnum;
import com.meida.module.user.client.entity.AppSchool;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 后台平台用户导出
 */
@Component
public class AppUserExportHandler implements ExportInterceptor<AppUser> {

    @Autowired
    private AppUserService appUserService;

    @Override
    public ResultBody initData(Map params) {
        CriteriaQuery<AppUser> cq = new CriteriaQuery<>(params, AppUser.class);
        cq.select(AppUser.class, "*");
        cq.likeByField(AppUser.class, "userName");
        cq.likeByField(AppUser.class, "nickName");
        cq.ge("DATE_FORMAT(user.createTime,'%Y-%m-%d')", cq.getParams("beginDate"));
        cq.le("DATE_FORMAT(user.createTime,'%Y-%m-%d')", cq.getParams("endDate"));
        cq.eq(AppUser.class, "userType");
        cq.eq(AppUser.class, "mobile");
        cq.like(AppUser.class, "birthday");
        cq.eq(AppUser.class, "status");
        cq.eq(AppUser.class, "deptId");
        cq.eq(AppUser.class, "positionId");
        cq.select(AppSchool.class, "schoolName");
        cq.select(BusScholartyrant.class, "roleTagName");
        cq.like(BusScholartyrant.class, "roleTagName");
        cq.createJoin(AppSchool.class).setMainField("schoolId").setJoinField("schoolId");
        cq.createJoin(BusScholartyrant.class).setMainField("userId").setJoinField("scholartyrantId");
        List<EntityMap> entityMapList = appUserService.selectEntityMap(cq);
        entityMapList.forEach(entityMap -> {
            String userType = entityMap.get("userType");
            UserTypeEnum userTypeEnum = UserTypeEnum.getByValue(userType);
            if (FlymeUtils.isNotEmpty(userTypeEnum)) {
                entityMap.put("userType", userTypeEnum.getLabel());
            }
            Integer sex = entityMap.getInt("sex");
            if (sex == 0) {
                entityMap.put("sex", "未知");
            }
            if (sex == 1) {
                entityMap.put("sex", "男");
            }
            if (sex == 2) {
                entityMap.put("sex", "女");
            }
            Integer status = entityMap.getInt("status");
            if (status == 0) {
                entityMap.put("status", "启用");
            }
            if (status == 1) {
                entityMap.put("status", "禁用");
            }
        });
        return ResultBody.ok(entityMapList);
    }

}
